package com.gt.web.srv.filter;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.gt.web.api.common.R;
import com.gt.web.api.exception.BusinessException;
import com.gt.web.srv.auth.JwtInfo;
import com.gt.web.srv.auth.TokenAuthentication;
import org.springframework.security.core.context.SecurityContextHolder;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * API访问权限控制
 */
@WebFilter(urlPatterns = {"/after/*"},filterName = "TokenAuthorFilter")
public class TokenAuthorFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse rep = (HttpServletResponse) response;
        rep.setHeader("Access-Control-Allow-Origin", "*");
        rep.setHeader("Access-Control-Allow-Methods","POST, GET, PUT, OPTIONS, DELETE, PATCH");
        String token = req.getHeader("ezr-sso-user");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter writer = null;
        if (StrUtil.isBlank(token)) {

            R<Object> fail = R.fail(401, "未登录,想干啥");
            try {
                writer = response.getWriter();
                writer.print(JSONUtil.toJsonStr(fail));

            }
            catch (IOException e) {
                //log.error("response error", e);
            }
            finally {
                if (writer != null)
                    writer.close();
            }
        }
        else {
            JwtInfo tokenInfo = null;
            try {
                tokenInfo = JwtInfo.parse(token);
            }
            catch (BusinessException e) {
                writer = response.getWriter();
                writer.print(JSONUtil.toJsonStr(R.fail(e.getCode(),e.getMsg())));
            }
            finally {
                if (writer != null)
                    writer.close();
            }
            SecurityContextHolder.getContext().setAuthentication(new TokenAuthentication(tokenInfo));
            chain.doFilter(request, response);
            return;
        }

        return;
    }

    @Override
    public void destroy() {

    }
}
